package com.hqyj.paimaisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hqyj.paimaisys.dao.DealrecordDao;
import com.hqyj.paimaisys.dao.HuiyuanDao;
import com.hqyj.paimaisys.dao.JingpaiDao;
import com.hqyj.paimaisys.model.Auction;
import com.hqyj.paimaisys.dao.AuctionDao;
import com.hqyj.paimaisys.model.Dealrecord;
import com.hqyj.paimaisys.model.Huiyuan;
import com.hqyj.paimaisys.model.Jingpai;
import com.hqyj.paimaisys.service.AuctionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2024-10-20
 */
@Service
public class AuctionServiceImpl extends ServiceImpl<AuctionDao, Auction> implements AuctionService {

    @Autowired
    private HuiyuanDao huiyuanDao;

    @Autowired
    private JingpaiDao jingpaiDao;

    @Autowired
    private DealrecordDao dealrecordDao;


    /**
     * 立即竞拍 : 有任何异常都回滚
     *             通过了以上验证，那么就可以竞拍
     *             1. 扣会员的押金
     *             2. 给 拍品设置最新竞拍者和竞拍价
     *             3. 在竞拍记录表中插入一条信息
     * @param aid : 竞拍者
     * @param nprice： 竞拍价
     * @param hid ：  会员账号
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean  jingpai(Integer aid, Integer nprice, String hid)  {
        //乐观锁
        //  1. select  count, anum  from auction;
        //查询拍品对象
        Auction auction = baseMapper.selectById(aid);
        // 本地的乐观锁
        Integer version = auction.getAnum();
        Huiyuan huiyuan = huiyuanDao.selectById(hid);
        //扣会员押金   update huiyuan set hicemoney =  hicemoney + uction.getAbmoney(), hyue = hyue- abmoney  where hid=?
        UpdateWrapper<Huiyuan> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("hicemoney", huiyuan.getHicemoney() + auction.getAbmoney())
                    .set("hyue", huiyuan.getHyue() - auction.getAbmoney())
                    .eq("hid", hid);
        huiyuanDao.update(null, updateWrapper);
        //如果有上一个人，退还保证金
        if(auction.getHid() != null){

            //查询上一个竞拍者
            Huiyuan last = huiyuanDao.selectById(auction.getHid());

            //修改他的余额和冻结金额        hicemoney = hicemoney-保证金,  yue = yue + 保证金
            UpdateWrapper<Huiyuan> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.set("hicemoney", last.getHicemoney() - auction.getAbmoney())
                    .set("hyue", last.getHyue() + auction.getAbmoney())
                    .eq("hid", last.getHid());
            huiyuanDao.update(null, updateWrapper2);

        }
        // update auction set nprice = ? , hid = ? where aid =?
        //  2. update  tb1 set nprice, hid, anum+1  where anum = 本地的anum
        UpdateWrapper<Auction> updateWrapper1 =  new UpdateWrapper<Auction>();
        updateWrapper1.set("nprice", nprice);
        updateWrapper1.set("hid",hid);
        updateWrapper1.set("anum",version +1);

        updateWrapper1.eq("aid",aid);
        updateWrapper1.eq("anum", version);
/*try {
    TimeUnit.SECONDS.sleep(60);
}
catch (Exception e){
    e.printStackTrace();
}*/
        //result 代表 修改成功的个数， 如果=0， 代表你抢购失败
        int result = baseMapper.update(null, updateWrapper1);
        if(result == 0){
            throw  new RuntimeException("手速慢了");
        }
        // 插入竞拍记录表
        Jingpai jingpai = new Jingpai();
        jingpai.setAid(aid);
        jingpai.setJprice(nprice);
        jingpai.setHid(hid);
        jingpaiDao.insert(jingpai);

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void endAuction() {
        //1。 查询今天要结束竞拍的拍品列表
        //   where etime=?  and state = 4
        QueryWrapper<Auction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", Auction.STATUS_AUCTING);
        queryWrapper.eq("etime", LocalDate.now().toString());
        List<Auction> auclist = baseMapper.selectList(queryWrapper);
       //2.  遍历拍品列表    a. 生成交易记录表     b. auction 的状态改为竞拍结束
        auclist.forEach(auction -> {
            Dealrecord dealrecord = new Dealrecord();
            dealrecord.setAid(auction.getAid());
            dealrecord.setGname(auction.getGname());
            if(auction.getHid() == null){
                dealrecord.setDid(Dealrecord.STATUS_LIUPAI);
            }else{
                dealrecord.setDid(Dealrecord.STATUS_DAIFUKUAN);
                dealrecord.setCjmoney(auction.getNprice());
                dealrecord.setHid(auction.getHid());
                dealrecord.setHname(huiyuanDao.selectById(auction.getHid()).getHname());
            }
            dealrecordDao.insert(dealrecord);
        });

        UpdateWrapper<Auction> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state", Auction.STATUS_FINISH);
        queryWrapper.eq("state", Auction.STATUS_AUCTING);
        queryWrapper.eq("etime", LocalDate.now().toString());
        baseMapper.update(null, updateWrapper);
    }


}
